#include "stdafx.h"
#include "PatientEvent.h"


//Data structure:
//EventType	data[0]		-> type of event (for all events)
//(byte)	data[1]		-> size of the rest of the data structure
//(byte)	data[2]		-> type
//(char*)	data[2+]	-> value
int serializePatientEvent(PatientEvent event, char* buffer){
	u_int bytesWritten = sizeof(event.type) + strlen(event.value.c_str()); // the size of the rest of the buffer

	u_int buffer_size = getPatientBufferSize(event);
	ZeroMemory(buffer, buffer_size);

	if(buffer != NULL && buffer_size > 0){		

		buffer[0] = PATIENT_EVENT;
		buffer[1] = bytesWritten;
		buffer[2] = event.type;

		char* dst = (buffer + sizeof(PATIENT_EVENT) + sizeof(bytesWritten) + sizeof(event.value)); // gives an index to start writing the alarm message string
		const char* str = event.value.c_str();
		size_t len = strlen(event.value.c_str());
		// memcpy(dst, str, len); //  this is not working, nothing is being added to the buffer...
		//  do it in a for loop !

		for (u_int i = 0; i < len; i++) {
			buffer[i+3] = str[i];
		}

		return 0;
	}else{ 
		fprintf(stdout, "Meh. The buffer is NULL or the buffer_size is too small (0 or less)");
		return -1;
	}
}

//Data structure:
//EventType	data[0]		-> type of event (for all events)
//(byte)	data[1]		-> size of the rest of the data structure
//(byte)	data[2]		-> type
//(char*)	data[2+]	-> value

int deserializePatientEvent(char* buffer, PatientEvent *event){

	if(buffer != NULL){


		// event type is in the 0th spot
		
		event->type = buffer[2]; // type is in 2nd spot		

		//create pointer to text
		char* textPtr = (buffer + 3); 

		std::string eventText(textPtr);
		event->value = eventText;

		return 0;
	}else{
		fprintf(stdout, "Deserialization failed: Buffer not allocated or too small");
		return -1;
	}
}

int getPatientBufferSize(PatientEvent event) {
	u_int bytesWritten = sizeof(event.type) + strlen(event.value.c_str()); // the size of the rest of the buffer
	return sizeof(PATIENT_EVENT)/*here is possible error*/ + sizeof(bytesWritten) + sizeof(event.type) + strlen(event.value.c_str());
}
